package com.yuanduan.mplus.view;

import android.annotation.TargetApi;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.cj.framework.app.BaseActivity;
import com.cj.framework.app.BaseApplication;
import com.cj.framework.util.IOkHttp;
import com.cj.framework.util.Msg;
import com.cj.framework.util.OkHttpImp;
import com.yuanduan.mplus.R;
import com.yuanduan.mplus.config.Config;
import com.yuanduan.mplus.db.dao.UserDao;
import com.yuanduan.mplus.db.entity.User;
import com.yuanduan.mplus.model.entity.RS;
import com.yuanduan.mplus.model.entity.RSM;

import java.util.HashMap;
import java.util.Map;

/**
 * 注册界面
 */
public class RegisterActivity extends BaseActivity implements View.OnClickListener {
    private TextView tv_policy;
    private EditText et_phone;
    private EditText et_code;
    private EditText et_pwd;
    private EditText et_insurePwd;
    private CheckBox cb_policy;
    private TextView tv_getCheckCode;
    private ImageButton ib_cancel;
    private TextView tv_register;
    private ProgressDialog progressDialog;
    private IOkHttp iOkHttp;
    private String userPhone;
    private String userPwd;
    private String code;
    private String insureUserPwd;
    private boolean isPolicy;
    private IOkHttp.IHttpCallback callback=new IOkHttp.IHttpCallback() {
        @Override
        public void onResponse(Msg msg, int index) {
            switch(index){
                case 0:
                    dealwithCheckCode(msg);
                    break;
                case 1:
                    dealwithRegister(msg);
                    break;
            }
        }

        @Override
        public void onError(Exception e) {
            progressDialog.dismiss();
            Toast.makeText(RegisterActivity.this,"网络出错",Toast.LENGTH_SHORT).show();
        }
    };

    private void dealwithRegister(Msg msg) {
        int rsm=((RSM)Config.decry(msg.content(),RSM.class)).getRS();
        if(rsm!=1){
            Toast.makeText(RegisterActivity.this,"注册失败",Toast.LENGTH_SHORT).show();
        }else{
            UserDao userDao= BaseApplication.getDaoSession().getUserDao();
            User user=new User();
            user.setUserType("1");
            user.setUserPwd(userPwd);
            user.setUserPhone(userPhone);
            userDao.insert(user);
            openActivity(Main1Activity.class);
        }
    }

    private void dealwithCheckCode(Msg msg){
        progressDialog.dismiss();
        int rs=((RS)Config.decry(msg.content(),RS.class)).getRs();
        if(rs==1){
            Toast.makeText(RegisterActivity.this,"验证码发送成功",Toast.LENGTH_SHORT).show();
        }else{
            Toast.makeText(RegisterActivity.this,"验证码发送失败",Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void findId() {
        tv_policy= (TextView) findViewById(R.id.register_tv_policy);
        et_phone= (EditText) findViewById(R.id.register_et_phone);
        et_code= (EditText) findViewById(R.id.register_et_checkcode);
        et_pwd= (EditText) findViewById(R.id.register_et_pwd);
        et_insurePwd= (EditText) findViewById(R.id.register_et_insurePwd);
        tv_getCheckCode= (TextView) findViewById(R.id.register_tv_getCheckcode);
        cb_policy= (CheckBox) findViewById(R.id.register_cb_policy);
        ib_cancel= (ImageButton) findViewById(R.id.register_ib_cancel);
        tv_register= (TextView) findViewById(R.id.register_tv_reg);
    }

    @Override
    protected void logic() {
        iOkHttp=new OkHttpImp();
        progressDialog=new ProgressDialog(this);
        tv_register.setOnClickListener(this);
        tv_getCheckCode.setOnClickListener(this);
        ib_cancel.setOnClickListener(this);
        tv_policy.setOnClickListener(this);
        et_insurePwd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}
            @Override
            public void afterTextChanged(Editable s) {
                if(s.length()>0){
                    tv_register.setBackgroundResource(R.drawable.btn_login1);
                }else{
                    tv_register.setBackgroundResource(R.drawable.login_et);
                }
            }
        });
    }

    @Override
    protected int setLayout() {
        return R.layout.activity_register;
    }


    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.register_tv_getCheckcode:
                sendPhoneCheckcode();
                break;
            case R.id.register_tv_reg:
                register();
                break;
            case R.id.register_ib_cancel:
                this.finish();
                break;
            case R.id.register_tv_policy:
                openActivity(PolicyActivity.class);
        }
    }

    /**
     * 发送手机验证码
     */
    private void sendPhoneCheckcode(){
        userPhone=et_phone.getText().toString().trim();

        //检查用户手机号
        if(!checkPhoneNumber(userPhone,this)){
            Toast.makeText(this,"请输入正确的手机号码",Toast.LENGTH_SHORT).show();
            return;
        }
        //设置获取验证码按钮
        setTime();

        //发送网络请求
        sendCheckCode();

    }

    private void sendCheckCode(){
        HashMap<String,String> hashMap=new HashMap<>();
        hashMap.put("UserPhone",userPhone);
        iOkHttp.httpInfoPost(Config.URL+Config.PHONECHECKCODE,Config.translateMap(hashMap),callback,0);
    }



    /**
     * 检查手机号码是否正确
     * @param phoneNumber
     * @param context
     * @return
     */
    public boolean checkPhoneNumber(String phoneNumber, Context context){
        boolean flag=true;
        if(TextUtils.isEmpty(phoneNumber)){
            flag=false;
        }
        try {
            long number = Long.parseLong(phoneNumber);
        }catch(NumberFormatException e){
            flag=false;
        }
        if(phoneNumber.length()!=11){
            flag=false;
        }
        return flag;
    }

    /**
     * 发送验证码
     */
    private void register(){
        userPhone=et_phone.getText().toString().trim();
        code=et_code.getText().toString().trim();
        userPwd=et_pwd.getText().toString().trim();
        insureUserPwd=et_insurePwd.getText().toString().trim();
        isPolicy=cb_policy.isChecked();
        //检查信息
        if(!checkAll(userPhone,code,userPwd,insureUserPwd,isPolicy)){
            return;
        }
        progressDialog.show();
        sendRegisterMessage();

    }

    private void sendRegisterMessage() {
        HashMap<String,String> hashMap=new HashMap<>();
        hashMap.put("UserPhone",userPhone);
        hashMap.put("Code",code);
        hashMap.put("Password1",userPwd);
        hashMap.put("Password2",insureUserPwd);
        hashMap.put("Agreed",isPolicy==true?"1":"0");
        iOkHttp.httpInfoPost(Config.URL+Config.USERREGISTRATION,Config.translateMap(hashMap),callback,1);
    }

    /**
     * 发送注册之前检查所有信息
     * @param userPhone
     * @param code
     * @param userPwd
     * @param insureUserPwd
     * @param isPolicy
     * @return
     */
    private boolean checkAll(String userPhone, String code, String userPwd, String insureUserPwd, boolean isPolicy){
        if(!checkPhoneNumber(userPhone,this)){
            Toast.makeText(this,"请输入正确的手机号",Toast.LENGTH_SHORT).show();
            return false;
        }
        if(!checkCode(code)){
            Toast.makeText(this,"请输入正确的验证码",Toast.LENGTH_SHORT).show();
            return false;
        }
        if(TextUtils.isEmpty(userPwd)){
            Toast.makeText(this,"请输入密码",Toast.LENGTH_SHORT).show();
            return false;
        }
        if(TextUtils.isEmpty(insureUserPwd)){
            Toast.makeText(this,"请确认密码",Toast.LENGTH_SHORT).show();
            return  false;
        }
        if(!userPwd.equals(insureUserPwd)){
            Toast.makeText(this,"密码不一致",Toast.LENGTH_SHORT).show();
            return false;
        }
        if(!isPolicy){
            Toast.makeText(this,"请接受条款",Toast.LENGTH_SHORT).show();
            return  false;
        }
        return true;
    }

    /**
     * 检查验证码
     * @param code
     * @return
     */
    private boolean checkCode(String code){
        if(TextUtils.isEmpty(code)){
            return false;
        }
        try{
            int code1= Integer.parseInt(code);
        }catch (NumberFormatException e){
            return false;
        }
        if(code.length()!=6){
            return false;
        }
        return true;
    }

    /**
     * 设置时间
     */
    private int time=120;
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void setTime() {
        tv_getCheckCode.setClickable(false);
        final Handler handler=new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (time >= 1) {
                    time--;
                    tv_getCheckCode.setText(String.valueOf(time)+"s");
                    handler.postDelayed(this,1000);
                }else{
                    tv_getCheckCode.setText("获取验证码");
                    time=120;
                    tv_getCheckCode.setClickable(true);
                    tv_getCheckCode.setBackground(getResources().getDrawable(R.drawable.btn_login2));
                }
            }
        }, 1000);
    }
}
